#!/bin/bash

# 直接部署Nginx配置的一体化脚本
# 解决SSH连接问题，一次性完成所有操作

echo "🔧 开始一体化Nginx配置部署..."

# 通过SSH执行完整的部署流程
ssh root@47.237.10.129 << 'REMOTE_SCRIPT'

# 停止Nginx服务
echo "⏹️  停止Nginx服务..."
systemctl stop nginx

# 备份当前配置
echo "📦 备份当前配置..."
mkdir -p /root/nginx-backup-$(date +%Y%m%d-%H%M%S)
cp -r /etc/nginx/* /root/nginx-backup-$(date +%Y%m%d-%H%M%S)/ 2>/dev/null || true

# 完全清除旧配置
echo "🗑️  清除旧配置..."
rm -rf /etc/nginx/conf.d/*

# 重写主nginx.conf
echo "🔄 重写主nginx.conf..."
cat > /etc/nginx/nginx.conf << 'MAIN_CONF'
user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;

include /usr/share/nginx/modules/*.conf;

events {
    worker_connections 1024;
}

http {
    log_format main '$remote_addr - $remote_user [$time_local] "$request" '
                    '$status $body_bytes_sent "$http_referer" '
                    '"$http_user_agent" "$http_x_forwarded_for"';

    access_log /var/log/nginx/access.log main;
    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;
    keepalive_timeout 65;
    types_hash_max_size 2048;

    include /etc/nginx/mime.types;
    default_type application/octet-stream;

    # 速率限制
    limit_req_zone $binary_remote_addr zone=api:10m rate=10r/s;

    # 包含站点配置
    include /etc/nginx/conf.d/*.conf;
}
MAIN_CONF

# 创建站点配置
echo "🚀 创建站点配置..."
cat > /etc/nginx/conf.d/cu-mr-bull.conf << 'SITE_CONF'
# Upstream定义
upstream cu_mr_bull_api {
    server 127.0.0.1:3000;
    keepalive 32;
}

# HTTP重定向到HTTPS
server {
    listen 80;
    server_name api.cumrbull.com.sg admin.cumrbull.com.sg;
    return 301 https://$server_name$request_uri;
}

# HTTPS服务器 - 主API服务
server {
    listen 443 ssl http2;
    server_name api.cumrbull.com.sg;
    
    # SSL配置
    ssl_certificate /etc/nginx/ssl/fullchain.pem;
    ssl_certificate_key /etc/nginx/ssl/privkey.pem;
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384;
    ssl_prefer_server_ciphers off;
    
    # 健康检查
    location /health {
        proxy_pass http://cu_mr_bull_api;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_connect_timeout 5s;
        proxy_send_timeout 10s;
        proxy_read_timeout 10s;
    }
    
    # API接口
    location /api/ {
        limit_req zone=api burst=10 nodelay;
        proxy_pass http://cu_mr_bull_api;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_connect_timeout 5s;
        proxy_send_timeout 30s;
        proxy_read_timeout 30s;
    }
    
    # 根路径
    location / {
        root /var/www/html;
        index index.html;
        try_files $uri $uri/ /index.html;
    }
}

# HTTPS服务器 - 管理后台
server {
    listen 443 ssl http2;
    server_name admin.cumrbull.com.sg;
    
    # SSL配置
    ssl_certificate /etc/nginx/ssl/fullchain.pem;
    ssl_certificate_key /etc/nginx/ssl/privkey.pem;
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384;
    ssl_prefer_server_ciphers off;
    
    # API请求代理到后端
    location /api/ {
        limit_req zone=api burst=10 nodelay;
        proxy_pass http://cu_mr_bull_api;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_connect_timeout 5s;
        proxy_send_timeout 30s;
        proxy_read_timeout 30s;
    }
    
    # 管理后台前端
    location / {
        root /var/www/admin;
        index index.html;
        try_files $uri $uri/ /index.html;
    }
}
SITE_CONF

# 测试配置
echo "🧪 测试Nginx配置..."
if nginx -t; then
    echo "✅ 配置文件语法正确"
    # 启动Nginx
    echo "🚀 启动Nginx服务..."
    systemctl start nginx
    systemctl enable nginx
    echo "📊 Nginx服务状态:"
    systemctl status nginx --no-pager -l
    echo "🎉 部署完成！"
else
    echo "❌ 配置文件有语法错误:"
    nginx -t
    exit 1
fi

REMOTE_SCRIPT

echo "🔍 测试部署结果..."
echo "健康检查:"
curl -k https://api.cumrbull.com.sg/health
echo ""
echo "管理后台API测试:"
curl -k -X POST https://admin.cumrbull.com.sg/api/auth/login \
  -H "Content-Type: application/json" \
  -d '{"email":"test@example.com","password":"test"}'
echo ""